/**
 * Phase4 面板注册完整性验证脚本
 * 检查自定义面板是否完整注册到Right/index.tsx的过滤器中
 */

const fs = require('fs');
const path = require('path');

function validatePanelRegistration(componentName) {
  console.log(`🔍 验证 ${componentName} 的面板注册完整性...`);

  const results = {
    success: true,
    issues: [],
    warnings: []
  };

  try {
    // 1. 读取EditFields配置，提取自定义belongTo
    const editFieldsPath = 'src/components/editor/schema/edit/aiComponents.ts';
    const editFieldsContent = fs.readFileSync(editFieldsPath, 'utf8');

    const customPanels = extractCustomPanels(editFieldsContent, componentName);
    console.log(`📋 发现自定义面板: ${customPanels.join(', ')}`);

    // 2. 读取Right/index.tsx，检查过滤器配置
    const rightIndexPath = 'src/components/editor/Right/index.tsx';
    const rightIndexContent = fs.readFileSync(rightIndexPath, 'utf8');

    // 3. 验证过滤器数组
    const filterValidation = validateFilterArrays(rightIndexContent, customPanels);
    results.issues.push(...filterValidation.issues);
    results.warnings.push(...filterValidation.warnings);

    // 4. 验证渲染条件
    const renderValidation = validateRenderConditions(rightIndexContent, customPanels);
    results.issues.push(...renderValidation.issues);

    // 5. 验证默认展开配置
    const expandValidation = validateDefaultExpand(rightIndexContent, customPanels);
    results.issues.push(...expandValidation.issues);

    // 6. 验证headerMap映射
    const mapValidation = validateHeaderMapping(rightIndexContent, customPanels);
    results.issues.push(...mapValidation.issues);

    if (results.issues.length > 0) {
      results.success = false;
    }

  } catch (error) {
    results.success = false;
    results.issues.push(`验证过程出错: ${error.message}`);
  }

  return results;
}

function extractCustomPanels(editFieldsContent, componentName) {
  const customPanels = [];
  const regex = new RegExp(`${componentName}:\\s*\\[([\\s\\S]*?)\\]`, 'g');
  const match = regex.exec(editFieldsContent);

  if (match) {
    const fieldsArray = match[1];
    const belongToMatches = fieldsArray.match(/belongTo:\s*['"`]([^'"`]+)['"`]/g);

    if (belongToMatches) {
      belongToMatches.forEach(match => {
        const belongTo = match.match(/belongTo:\s*['"`]([^'"`]+)['"`]/)[1];
        if (belongTo.startsWith('render') && !customPanels.includes(belongTo)) {
          customPanels.push(belongTo);
        }
      });
    }
  }

  return customPanels;
}

function validateFilterArrays(content, customPanels) {
  const issues = [];
  const warnings = [];

  // 检查basicUploadPublishArr
  const basicArrayMatch = content.match(/basicUploadPublishArr.*?\[([\s\S]*?)\]/);
  if (basicArrayMatch) {
    const contentPanels = customPanels.filter(panel =>
      !panel.includes('Style') && !panel.includes('Chart')
    );

    contentPanels.forEach(panel => {
      if (!basicArrayMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Content面板 '${panel}' 未添加到 basicUploadPublishArr`);
      }
    });
  }

  // 检查stylePublishArr
  const styleArrayMatch = content.match(/stylePublishArr.*?\[([\s\S]*?)\]/);
  if (styleArrayMatch) {
    const stylePanels = customPanels.filter(panel =>
      panel.includes('Style') || panel.includes('Chart')
    );

    stylePanels.forEach(panel => {
      if (!styleArrayMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Style面板 '${panel}' 未添加到 stylePublishArr`);
      }
    });
  }

  return { issues, warnings };
}

function validateRenderConditions(content, customPanels) {
  const issues = [];

  // 检查getRenderContent条件
  const getRenderContentMatch = content.match(/getRenderContent.*?\[([\s\S]*?)\]/);
  if (getRenderContentMatch) {
    const contentPanels = customPanels.filter(panel =>
      !panel.includes('Style') && !panel.includes('Chart')
    );

    contentPanels.forEach(panel => {
      if (!getRenderContentMatch[1].includes(`'${panel}'`)) {
        issues.push(`❌ Content面板 '${panel}' 未添加到 getRenderContent 条件检查`);
      }
    });
  }

  return { issues };
}

function validateDefaultExpand(content, customPanels) {
  const issues = [];

  // 检查defaultActiveKey配置
  const defaultActiveKeyMatches = content.match(/defaultActiveKey:\s*\[([\s\S]*?)\]/g);

  customPanels.forEach(panel => {
    let found = false;
    defaultActiveKeyMatches.forEach(match => {
      if (match.includes(`'${panel}'`)) {
        found = true;
      }
    });

    if (!found) {
      issues.push(`⚠️ 面板 '${panel}' 未添加到 defaultActiveKey（可选，影响默认展开）`);
    }
  });

  return { issues };
}

function validateHeaderMapping(content, customPanels) {
  const issues = [];

  customPanels.forEach(panel => {
    const headerMapPattern = new RegExp(`${panel}:\\s*\\{[\\s\\S]*?render:`, 'g');
    if (!headerMapPattern.test(content)) {
      issues.push(`❌ 面板 '${panel}' 未在 headerMap 中配置映射关系`);
    }
  });

  return { issues };
}

// 命令行调用
if (require.main === module) {
  const componentName = process.argv[2];
  if (!componentName) {
    console.error('❌ 请提供组件名称: node phase4-panel-validation.js <ComponentName>');
    process.exit(1);
  }

  const result = validatePanelRegistration(componentName);

  console.log('\n📊 验证结果:');

  if (result.success) {
    console.log('✅ 面板注册完整性验证通过');
  } else {
    console.log('❌ 发现面板注册问题:');
    result.issues.forEach(issue => console.log(`  ${issue}`));
  }

  if (result.warnings.length > 0) {
    console.log('\n⚠️ 警告:');
    result.warnings.forEach(warning => console.log(`  ${warning}`));
  }

  console.log('\n📋 修复建议:');
  console.log('1. 检查 src/components/editor/Right/index.tsx');
  console.log('2. 确保自定义面板添加到相应的过滤器数组');
  console.log('3. 更新渲染条件和默认展开配置');
  console.log('4. 重新测试面板显示功能');

  process.exit(result.success ? 0 : 1);
}

module.exports = { validatePanelRegistration };